#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# Copyright [Gtlions Lai].
# Create Date:
# Update Date:
"""summarization ahout this script.

detail ahout this script

   Class(): summarization about Class
   ...
   function(): summarization about function
   ...
"""
__authors__ = '"Gtlions Lai" <gtlions.l@qq.com>'
import os
import sys
import cmd
import time
import sqlite3


# select substr(file,1,position) file,count(*) from fileinfos group by 1 order by 2 desc limit 10;
# select * from pg_class where oid=file;
# select * from pg_class where relfilenode=file;
class GatherFilesInfo(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        current_time = time.strftime('%Y/%m/%d %H:%M:%S', time.localtime(time.time()))
        self.prompt = "(::GatherFileInfo::)>>"
        self.intro = "--------------------------------------------\n" \
                     + "|       Welcome GatherFileInfos App        |\n" \
                     + "|       Try help for more information      |" \
                     + "\n|             By Gtlions Lai               |\n|           " \
                     + current_time \
                     + "            |\n--------------------------------------------\n"
        self.dbname = 'gatherfilesinfo.dbf'
        self.cwd = os.getcwd()

        if os.path.isfile(self.dbname):
            pass
        else:
            os.system('''sqlite3 ''' + self.dbname + ''' <<EOF
.quit
EOF''')

    def help_exit(self):
        print "Exit App."

    def do_exit(self, line):
        sys.exit()

    def help_gather(self):
        print "Gather Dirs Files Infos,usage: gather <dirs-path>."

    def do_gather(self, path):
        if path == "": path = raw_input('input dirs-path: ')
        if path == '.':
            path = self.cwd
        print '\nWill Gather [' + path + '] Files Info.\n'

        current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())

        db = sqlite3.connect(self.dbname)
        cursor = db.cursor()
        cursor.execute("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='fileinfos';")
        # print cursor.fetchall()[0][0]
        if cursor.fetchall()[0][0] == 0:
            cursor.execute(
                "CREATE TABLE fileinfos(ctime timestamp,dir varchar2(2000),file varchar2(2000),position INT,size varchar2(2000));")
        else:
            pass
        dfile = {}
        for root, dirs, files in os.walk(path):
            # print '---[dir]---', root, dirs, files
            try:
                for singlefile in files:
                    singlefile = os.path.join(root, singlefile)
                    # print '   ---[file]---', singlefile
                    dfile[singlefile] = os.stat(singlefile).st_size
                for filename, size in dfile.items():
                    cursor.execute("INSERT INTO fileinfos VALUES(:1,:2,:3,:4,:5)",
                                   (
                                       current_time, unicode(root, "utf-8"), unicode(filename, "utf-8"),
                                       filename.find('.'),
                                       size))
                dfile.clear()
            except OSError, e:
                pass
        print '..............'
        print '\nGather [' + path + '] Files Info Done.\n'
        db.commit()
        db.close()

    def help_clear(self):
        print "Clear Gather Results,usage: clear."

    def do_clear(self, path):
        db = sqlite3.connect(self.dbname)
        cursor = db.cursor()
        cursor.execute("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='fileinfos';")
        if cursor.fetchall()[0][0] == 0:
            pass
        else:
            cursor.execute("DELETE FROM fileinfos;")
            cursor.execute("VACUUM;")
            db.commit()
            db.close()

    def help_showtop(self):
        print "Show Gather Results,usage: show -linelimit."

    def do_showtop(self, linelimit):
        if linelimit == "": linelimit = raw_input('input linelimit: ')
        db = sqlite3.connect(self.dbname)
        cursor = db.cursor()
        cursor.execute("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='fileinfos';")
        if cursor.fetchall()[0][0] == 0:
            pass
        else:
            print '---------------------------------------------------------------'
            print '|CTIME              |    DIRS    |   FILENAME    |   FILENUMS|'
            print '---------------------------------------------------------------'
            prectime = ''
            currentctime = ''
            predir = ''
            currentdir = ''

            cursor.execute(
                "select ctime,dir,substr(file,1,position) filename,count(*) nums from fileinfos group by ctime,dir,filename order by nums desc limit " + linelimit + ";")
            for ret in cursor.fetchall():
                currentctime = ret[0]
                currentdir = ret[1]
                if predir:
                    if predir == currentdir and prectime == currentctime:
                        print '|', ''.ljust(len(ret[0])), '|', ''.ljust(len(ret[1])), '|', ret[2], '|', ret[3], '|'
                    else:
                        print '|', ret[0], '|', ret[1], '|', ret[2], '|', ret[3], '|'
                    prectime = ret[0]
                    predir = ret[1]
                else:
                    print '|', ret[0], '|', ret[1], '|', ret[2], '|', ret[3], '|'
                    prectime = ret[0]
                    currentctime = ret[0]
                    predir = ret[1]
                    currentdir = ret[1]
            db.commit()
            db.close()

    def help_show(self):
        print "Show Gather Results,usage: show."

    def do_show(self, linelimit):
        db = sqlite3.connect(self.dbname)
        cursor = db.cursor()
        cursor.execute("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='fileinfos';")
        if cursor.fetchall()[0][0] == 0:
            pass
        else:
            print '---------------------------------------------------------------'
            print '|CTIME              |    DIRS    |   FILENAME|'
            print '---------------------------------------------------------------'
            prectime = ''
            currentctime = ''
            predir = ''
            currentdir = ''

            cursor.execute(
                "SELECT ctime,dir,file nums FROM fileinfos ORDER BY 1,2,3;")
            for ret in cursor.fetchall():
                currentctime = ret[0]
                currentdir = ret[1]
                if predir:
                    if predir == currentdir and prectime == currentctime:
                        print '|', ''.ljust(len(ret[0])), '|', ''.ljust(len(ret[1])), '|', ret[2], '|'
                    else:
                        print '|', ret[0], '|', ret[1], '|', ret[2], '|'
                    prectime = ret[0]
                    predir = ret[1]
                else:
                    print '|', ret[0], '|', ret[1], '|', ret[2], '|'
                    prectime = ret[0]
                    currentctime = ret[0]
                    predir = ret[1]
                    currentdir = ret[1]
            db.commit()
            db.close()


if __name__ == '__main__':
    gfi = GatherFilesInfo()
    gfi.cmdloop()
